package com.globallogic.training.javase.tree;

/**
 * Binary tree implementation.
 *  
 * @author Artem.Zeltinsh
 */
public class NodeImpl implements Node{

	private String value;

	private Node left;

	private Node right;

	public NodeImpl(String value) {
		this.value = value;
	}

	public String getValue() {
		return value;
	}

	public Node getLeftChild() {
		return left;
	}

	public Node getRightChild() {
		return right;
	}
	
	public Node addNode(String value) {
		
		if (this.value.equals(value)) {
			return this;
		}
		
		if (this.value.compareTo(value) > 0) {
			if (left == null) {
				return left = new NodeImpl(value);
			} else {
				return left.addNode(value);
			}
		} else {
			if (right == null)
				return right = new NodeImpl(value);
			else
				return right.addNode(value);
		}
	}
	
	public boolean isLeaf() {
		return left == null && right == null;
	}

	public int getHeight() {

		if (isLeaf()) {
			return 0;
		}

		int result = 1;
		if (left != null && right != null) {
			result += Math.max(left.getHeight(), right.getHeight());
		} else if (left != null) {
			result += left.getHeight();
		} else {
			result += right.getHeight();
		} 
		return result++;
	}

	@Override
	public String toString() {

		StringBuilder sb = new StringBuilder();
		sb.append(value);

		if (left != null || right != null) {
			sb.append("(");
			sb.append(left != null ? left : "");
			sb.append(",");
			sb.append(right != null ? right : "");
			sb.append(")");
		}
		
		return sb.toString();
	}
}